package com.sxdz.web.order

import com.sxdz.constant.CommonConstant
import com.sxdz.constant.MessageConstant
import com.sxdz.controller.service.order.IOrderDetailService
import com.sxdz.controller.service.order.IOrderService
import com.sxdz.controller.service.order.OrderService
import com.sxdz.controller.service.wechat.IWechatSubService
import com.sxdz.models.TOrder
import com.sxdz.models.TOrderDetail
import com.sxdz.models.TblWechatSubscribe
import com.sxdz.models.common.JsonResult
import com.sxdz.models.common.Order
import com.sxdz.models.common.RollPage
import com.toolbox.utils.DateUtil
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

import java.text.SimpleDateFormat

/**
 * Created by LiYan on 2016/8/2.
 * update by lzw on 2016/8/23
 * 订单信息
 */
@RestController
@CompileStatic
@TypeChecked
@RequestMapping("order")
class OrderAction {
    Logger logger = LoggerFactory.getLogger(this.getClass())
    @Autowired
    private IOrderService orderService

    @Autowired
    private IOrderDetailService orderDetailService

    @Autowired
    private IWechatSubService wechatSubService;
    /**
     * 按日期范围查询订单
     * @param startTime
     * @param endTime
     * @param openId
     * @param pageNum 当前页码
     * @return
     */
    @RequestMapping(value = "getOrders", method = RequestMethod.GET)
    @ResponseBody
    queryOrder(String dateType,String openId, @RequestParam(value="pageNum",defaultValue = "1")String pageNum,String payStatus){
        def params=[:]
        Integer pageSize=10;
        String timestart;
        String timeend;
        try{
        TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openId] as Map)
        if (wechatSubscribe == null) {
            return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
        }
        if(dateType=="1"){

            //获取当前的年份和月份
            SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd")
            Calendar calendar = Calendar.getInstance()
            timestart = myFormat.format(calendar.getTime())+" 00:00:00"
            timeend = myFormat.format(calendar.getTime())+" 23:59:59"

            //String类型转换成Long格式的时间
            timestart = DateUtil.formatDateString(timestart)
            timeend = DateUtil.formatDateString(timeend)

        }else if(dateType=="3"){

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Calendar nowOld=Calendar.getInstance();
            nowOld.add(Calendar.MONTH,-3);//三个月前
            timestart = formatter.format(nowOld.getTime())+" 00:00:00"

            SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd")
            Calendar calendar = Calendar.getInstance()
            timeend = myFormat.format(calendar.getTime())+" 23:59:59"
            //String类型转换成Long格式的时间
            timestart = DateUtil.formatDateString(timestart)
            timeend = DateUtil.formatDateString(timeend)

        }else if(dateType=="6"){

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Calendar nowOld=Calendar.getInstance();
            nowOld.add(Calendar.MONTH,-6);//半年前
            timestart = formatter.format(nowOld.getTime())+" 00:00:00"

            SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd")
            Calendar calendar = Calendar.getInstance()
            timeend = myFormat.format(calendar.getTime())+" 23:59:59"

            //String类型转换成Long格式的时间
            timestart = DateUtil.formatDateString(timestart)
            timeend = DateUtil.formatDateString(timeend)
        }else if(dateType=="12"){

            //代表需要一年内的数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
            Calendar calendar=Calendar.getInstance();
            timestart = formatter.format(calendar.getTime())+"-01-01 00:00:00"
            timeend = formatter.format(calendar.getTime())+"-12-31 23:59:59"
            //String类型转换成Long格式的时间
            timestart = DateUtil.formatDateString(timestart)
            timeend = DateUtil.formatDateString(timeend)
        }
        params<<[startTime:timestart]<<[endTime:timeend]
        params<<[userId:wechatSubscribe.getSubcribeId()]
        params<<[pageNum:pageNum]
        params<<[payStatus:payStatus]
        params<<[goodsModule2:"1,4"]
        RollPage rollPage=orderService.findListPageByParams(params,Order.desc("create_time"),Integer.parseInt(pageNum),pageSize)
        return new JsonResult<Object>(MessageConstant.SUCCESS,rollPage)
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<Object>(MessageConstant.SYS_ERROR,"系统异常");
        }
    }

    /**
     * 按日期范围查询缴费记录
     * @param startTime
     * @param endTime
     * @param openId
     * @param pageNum 当前页码
     * @return
     */
    @RequestMapping(value = "getRecharges", method = RequestMethod.GET)
    @ResponseBody
    getRecharges(String dateType,String openId, @RequestParam(value="pageNum",defaultValue = "1")String pageNum){
        def params=[:]
        Integer pageSize=10;
        String timestart;
        String timeend;
        try{
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openId] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            if(dateType=="1"){

                //获取当前的年份和月份
                SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd")
                Calendar calendar = Calendar.getInstance()
                timestart = myFormat.format(calendar.getTime())+" 00:00:00"
                timeend = myFormat.format(calendar.getTime())+" 23:59:59"

                //String类型转换成Long格式的时间
                timestart = DateUtil.formatDateString(timestart)
                timeend = DateUtil.formatDateString(timeend)

            }else if(dateType=="3"){

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Calendar nowOld=Calendar.getInstance();
                nowOld.add(Calendar.MONTH,-3);//三个月前
                timestart = formatter.format(nowOld.getTime())+" 00:00:00"

                SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd")
                Calendar calendar = Calendar.getInstance()
                timeend = myFormat.format(calendar.getTime())+" 23:59:59"
                //String类型转换成Long格式的时间
                timestart = DateUtil.formatDateString(timestart)
                timeend = DateUtil.formatDateString(timeend)

            }else if(dateType=="6"){

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Calendar nowOld=Calendar.getInstance();
                nowOld.add(Calendar.MONTH,-6);//半年前
                timestart = formatter.format(nowOld.getTime())+" 00:00:00"

                SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd")
                Calendar calendar = Calendar.getInstance()
                timeend = myFormat.format(calendar.getTime())+" 23:59:59"

                //String类型转换成Long格式的时间
                timestart = DateUtil.formatDateString(timestart)
                timeend = DateUtil.formatDateString(timeend)
            }else if(dateType=="12"){

                //代表需要一年内的数据
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
                Calendar calendar=Calendar.getInstance();
                timestart = formatter.format(calendar.getTime())+"-01-01 00:00:00"
                timeend = formatter.format(calendar.getTime())+"-12-31 23:59:59"
                //String类型转换成Long格式的时间
                timestart = DateUtil.formatDateString(timestart)
                timeend = DateUtil.formatDateString(timeend)
            }
            params<<[startTime:timestart]<<[endTime:timeend]
            params<<[userId:wechatSubscribe.getSubcribeId()]
            params<<[pageNum:pageNum]
            params<<[payStatus:CommonConstant.PayStatus.PaySuccess.value.toString()]//默认支付成功
            params<<[goodsModule:"3"]
            RollPage rollPage=orderService.findListPageByParams(params,Order.desc("create_time"),Integer.parseInt(pageNum),pageSize)
            return new JsonResult<Object>(MessageConstant.SUCCESS,rollPage)
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<Object>(MessageConstant.SYS_ERROR,"系统异常");
        }
    }

    /**
     *查询orderDetail
     * @param orderId
     * @return
     */
    @RequestMapping(value = "getOrderDetail/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    queryOrderDetail(@PathVariable("orderId")Long orderId){
        def param=[:]
        param<<[orderId:orderId]
        try{
        List<TOrderDetail> orderDetail =new ArrayList<TOrderDetail>()
        orderDetail=orderDetailService.findListByParams(param)
        if(null==orderDetail||orderDetail.size()==0){
            logger.info("未查询到orderDetail信息")
            return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
        }else{
            return new JsonResult<Object>(MessageConstant.SUCCESS,orderDetail)
        }
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<Object>(MessageConstant.SYS_ERROR,"系统异常");
        }

    }

    /**
     *查询order
     * @param id
     * @return
     */
    @RequestMapping(value = "getOrder/{id}", method = RequestMethod.GET)
    @ResponseBody
    queryOrder(@PathVariable("id")String id){
        try{
            if(id==null || "".equals(id)){
                return new JsonResult<Object>(MessageConstant.ERR_PARAMETER,"订单id不能为空")
            }
            Object obj=orderService.findObjByKey(id as Long)
            TOrder order;
            if(obj!=null){
             order=obj as TOrder;
                return new JsonResult<Object>(MessageConstant.SUCCESS,order)
            }else{
                logger.info("未查询到订单信息")
                return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
            }
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<Object>(MessageConstant.SYS_ERROR,"系统异常");
        }

    }
    /**
     * 按支付状态查询
     * @param orderStatus  订单状态
     * @param pageNum   页码
     * 备注：和第一个有点重复
     * @return
     */
    @RequestMapping(value = "queryOrderStatus/{orderStatus}", method = RequestMethod.GET)
    queryOrderPayStatus(@RequestParam(value="pageNum",defaultValue = "1")String pageNum,@RequestParam("orderStatus")String  orderStatus,String openid){
        try{
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            Integer pageSize=10;
            Map<String,Object> params=[:];
            params<<[payStatus:orderStatus];
            params<<[userId:wechatSubscribe.getSubcribeId()];
            RollPage rollPage=orderService.findListPageByParams(params,Order.desc("create_time"),Integer.parseInt(pageNum),pageSize)
       //List<TOrder> payList=orderService.findListByStatus(orderStatus);
            return new JsonResult<Object>(MessageConstant.SUCCESS,rollPage)
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<Object>(MessageConstant.SYS_ERROR,"系统异常");
        }

    }

    /**
     * 删除订单
     * @return
     */
    @RequestMapping(value = "delOrders/{orderId}", method = RequestMethod.GET)
    delOrder(@PathVariable("orderId")Long  orderId){
        try {
            int orderDetail=orderDetailService.deleteOrder(orderId);
            int  orderCount=orderService.deleteOrder(orderId);
            if (orderDetail>0&&orderCount>0){
                return new JsonResult<Object>(MessageConstant.SUCCESS,"删除订单成功")
            }else{
                return new JsonResult<Object>(MessageConstant.FAILURE,"删除订单失败")
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

}
